package com.my.chapter14;

import java.lang.reflect.Field;
import java.util.HashSet;
import java.util.Set;

public class practice9 {
    public static void main(String[] args) throws ClassNotFoundException {
        GetDeclaredFields.main(new String[]{"com.my.chapter14.Derived"});
    }
}

interface Iface {
    int i = 47;
    void f();
}

class Base implements Iface {
    String s;
    double d;
    public void f() { System.out.println("Base.f"); }
}

class Composed {
    Base b;
}

class Derived extends Base {
    Composed c;
    String s;
}

class GetDeclaredFields{
    static Set<Class<?>> alreadyDisplayed =
            new HashSet<Class<?>>();
    static void printClasses(Class<?> c) {
        if(c == null) return;
        System.out.println("The Class is " + c.getSimpleName());
        Field[] fields = c.getDeclaredFields();
        if(fields.length != 0)
            System.out.println("Fields:");
        for(Field fld : fields) {
            System.out.println(" " + fld);
        }

        Class[] classes =  c.getInterfaces();
        if(classes.length != 0){
            System.out.println("Interface:");
        }
        for(Class<?> k : c.getInterfaces())
            System.out.println(" " + k.getName());

        for(Field fld : fields) {
            Class<?> k = fld.getType();
            if(!alreadyDisplayed.contains(k)) {
                printClasses(k);
                alreadyDisplayed.add(k);
            }
        }
        for(Class<?> k : c.getInterfaces()) {
            printClasses(k.getSuperclass());
        }
        printClasses(c.getSuperclass());
    }

    public static void main(String[] args) throws ClassNotFoundException {
        for(int i = 0; i < args.length; i++) {
            System.out.println("Displaying " + args[i]);
            printClasses(Class.forName(args[i]));
            if(i < args.length - 1)
                System.out.println("==================");
        }
    }
}
